package com.kyzh.core.adapters

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import com.gushenge.core.beans.Collection
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.R
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import org.jetbrains.anko.toast

class CollectionTabAdapter(val context: Context):PagerAdapter() {

    var p1 = 1
    var max1 = 1
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val view = View.inflate(context, R.layout.recyclerview,null)
        val root = view.findViewById<SmartRefreshLayout>(R.id.root)
        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)


        val beans = arrayListOf<Collection>()
        val t = if (position == 1) 2 else 1
        recyclerView.layoutManager = object : GridLayoutManager(context, t){
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        p1=1
        max1=1
        val adapter = CollectionAdapter(beans)
        recyclerView.adapter = adapter
        root.autoRefresh()
        root.setEnableAutoLoadMore(false)
        root.setOnRefreshListener {
            p1=1
            addData(root,beans,adapter,position)
        }

        root.setOnLoadMoreListener {
            if (p1>max1){
                context.toast(context.getString(R.string.noHaveMore))
                root.finishLoadMore()
            }else{
                addData(root,beans,adapter,position)
            }
        }


        container.addView(view)
        return view
    }


    private fun addData(root: SmartRefreshLayout, bean: ArrayList<Collection>, adapter: CollectionAdapter, position: Int) {
        UserImpl.myCollect(position,p1,object : ResultListener {
            override fun error() {
                adapter.setEmptyView(R.layout.empty)
                root.finishRefresh()
                root.finishLoadMore()
            }

            override fun success(beans: Any, p: Int, max: Int) {
                beans as ArrayList<Collection>
                root.finishRefresh()
                root.finishLoadMore()
                if (p == 2) {
                    bean.clear()
                }
                bean.addAll(beans)
                adapter.notifyDataSetChanged()
                p1 = p
                max1 = max
            }
        })
    }
    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object`as View)
    }
    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view==`object`
    }

    override fun getCount(): Int {
        return 2
    }
}